import { Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { In, Repository } from 'typeorm';
import { OrderGoodsEntity } from '../entity/goods';
import { UserInfoEntity } from '../../user/entity/info';
import { OrderShopEntity } from '../entity/shop';
import { AgentRelationService } from '../../agent/service/agent';
import { BaseSysUserEntity } from '../../base/entity/sys/user';

/**
 * 用户信息（门店业务）
 */
@Provide()
export class UserShopService extends BaseService {
  @InjectEntityModel(OrderGoodsEntity)
  orderGoodsEntity: Repository<OrderGoodsEntity>;

  @InjectEntityModel(UserInfoEntity)
  userInfoEntity: Repository<UserInfoEntity>;

  @InjectEntityModel(OrderShopEntity)
  orderShopEntity: Repository<OrderShopEntity>;

  @InjectEntityModel(BaseSysUserEntity)
  baseSysUserEntity: Repository<BaseSysUserEntity>;

  @Inject()
  agentRelationService: AgentRelationService;

  @Inject()
  ctx;

  // 新增用户
  async addUser(body) {
    console.log(body);
    // const res = await this.userInfoEntity.save(userInfo);
    if (!body.nickName || !body.phone || body.gender == 0 || !body.birthday) {
      throw new Error('请填写完整的信息');
    }
    if (!body.phone || !/^1[3-9]\d{9}$/.test(body.phone)) {
      throw new Error('请输入正确的手机号格式');
    }
    // 查询是否已录入手机号
    const hasUser = await this.userInfoEntity.findOne({
      where: {
        phone: body.phone,
      },
    });
    if (hasUser) {
      throw new Error('手机号已存在');
    }
    const admin = await this.baseSysUserEntity.findOne({
      where: {
        id: this.ctx.admin.userId,
      },
    });
    console.log('addUser', this.ctx.admin, admin);
    if (!admin.shopId) {
      throw new Error('请先绑定店铺');
    }
    const userInfo = new UserInfoEntity();
    userInfo.nickName = body.nickName;
    userInfo.phone = body.phone;
    userInfo.gender = body.gender;
    userInfo.birthday = body.birthday;
    userInfo.shopId = admin.shopId;
    userInfo.openid = '';
    const res = await this.userInfoEntity.save(userInfo);
    return res;
  }

  // 重写page方法
  async page(body) {
    console.log(body);
    const adminId = this.ctx.admin.userId;

    // 查询代理商以及下级代理的店铺，即所有店铺
    const shop = await this.agentRelationService.queryAgentShopIds(adminId);
    // 查询自己绑定的店铺
    // const shop = await this.orderShopEntity.findOne({
    //   where: {
    //     agentId: adminId,
    //   },
    // });
    if (!shop) {
      throw new Error('没有绑定店铺');
    }
    // 查询自己绑定店铺的用户
    // const queryBuilder = this.userInfoEntity.createQueryBuilder('userInfo')
    //   .where('userInfo.shopId = :shopId', {
    //     shopId: shop,
    //   });
    // 查询代理商以及下级代理店铺的用户
    const queryBuilder = this.userInfoEntity
      .createQueryBuilder('userInfo')
      .where('userInfo.shopId in (:shopId)', {
        shopId: shop,
      });

    if (body.merge) {
      if (body.nickName) {
        queryBuilder.andWhere(
          'userInfo.nickName = :nickName or userInfo.phone = :nickName',
          {
            nickName: body.nickName,
          }
        );
      } else {
        throw new Error('请输入用户名称或手机号');
      }
    } else {
      if (body.phone || body.nickName) {
        queryBuilder.andWhere(
          'userInfo.phone = :phone or userInfo.nickName = :nickName',
          {
            phone: body.phone,
            nickName: body.nickName,
          }
        );
      }
    }
    // 如果body里面有shopId则查询
    if (body.shopId) {
      queryBuilder.andWhere('userInfo.shopId = :shopId', {
        shopId: body.shopId,
      });
    }
    // id倒序排序
    queryBuilder.orderBy('userInfo.id', 'DESC');

    // 店铺信息
    const shopList = await this.orderShopEntity.find({
      select: ['id', 'name'],
    });

    queryBuilder.select([
      'userInfo.id as id',
      'userInfo.nickName as nickName',
      'userInfo.phone as phone',
      'userInfo.gender as gender',
      'userInfo.birthday as birthday',
      'userInfo.shopId as shopId',
      'userInfo.remark as remark',
    ]);

    if (!body.isExport) {
      queryBuilder.skip((body.page - 1) * body.size).take(body.size);
    }

    const userList = await queryBuilder.getRawMany();

    userList.forEach(user => {
      user.shopName =
        shopList.find(shop => shop.id === user.shopId)?.name || '';
    });

    return {
      list: userList,
      pagination: {
        page: body.page,
        size: body.size,
        total: await queryBuilder.getCount(),
      },
    };
  }
}
